package com.wk.unreal.yyzxserver.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    public static final String KEY = "unreal";
    // 生成 token
    public static String getToken(Map<String,Object> claims) {
        // JWT 组成 header标头, Payload 有效载荷, Signature 签名
        String token =  JWT.create() //
                .withClaim("claims", claims) //
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12)) //
                .sign(Algorithm.HMAC256(KEY));
        return token;
    }

    // 验证 token
    public static Map<String,Object> parseToken (String token) {
        Map<String, Object> claims = JWT.require(Algorithm.HMAC256(KEY))//
                .build() //
                .verify(token) //
                .getClaim("claims") //
                .asMap();
        return claims;
    }

    public static void main(String[] args) {
        // 生成 TOKEN
//        Map<String, Object> claims = new HashMap<>();
//        claims.put("id", "1");
//        claims.put("username", "unreal");
//        String token = getToken(claims);
//        System.out.println(token);
    // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbXMiOnsiaWQiOiIxIiwidXNlcm5hbWUiOiJ1bnJlYWwifSwiZXhwIjoxNzMxMDA3ODMwfQ.8EXpg2lkYjREsiOfjvYZfdTMXf7P6zp5lvkWlZynO1I
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbXMiOnsiaWQiOiIxIiwidXNlcm5hbWUiOiJ1bnJlYWwifSwiZXhwIjoxNzMxMDA3ODMwfQ.8EXpg2lkYjREsiOfjvYZfdTMXf7P6zp5lvkWlZynO1I";
        // 验证 Token
        Map<String, Object> maps = parseToken(token);
        System.out.println(maps.get("id"));
    }

}
